package com.woniu.darryringmall.front.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.darryringmall.admin.jwt.Audience;
import com.woniu.darryringmall.admin.jwt.JwtUtil;
import com.woniu.darryringmall.front.entity.User;
import com.woniu.darryringmall.front.service.UserService;
import com.woniu.darryringmall.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller("frontController")
@RequestMapping("front/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private Audience audience;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 进入登录界面
     *
     * @return
     */
    @GetMapping("login")
    public String login() {
        return "login";
    }


    /**
     * 从登录界面取得账号和密码进行验证，通过了进入首页
     * @param user
     * @return
     */
    @PostMapping("login")
    @ResponseBody
    public ResponseData login(@RequestBody User user, HttpSession session) {
            QueryWrapper <User>queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("telephone",user.getTelephone()).or().eq("email",user.getEmail());
            User m = userService.getOne(queryWrapper);
        if (m == null) {
            return new ResponseData(404, "账号不正确");
        } else {
            if (!m.getPassword().equals(user.getPassword())) {
                return new ResponseData(405, "密码不正确");
            } else {
                session.setAttribute("user",m);
                System.out.println(session.getAttribute("user"));
                return new ResponseData(m.getName());
            }
        }
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @PostMapping("out")
    @ResponseBody
    private ResponseData out(HttpSession session){
        session.removeAttribute("user");
        return ResponseUtils.SUCCESS;
    }

    /**
     * 进入注册界面
     *
     * @return
     */
    @GetMapping("reg")
    public String reg() {
        return "reg";
    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("register")
    @ResponseBody
    public ResponseData reg( @RequestBody User user, BindingResult result) {
        System.out.println(user.getCode());
        System.out.println(user.getPassword());
        if(user.getCode()==null) {
            return new ResponseData(ResultStateCode.FAIL, "验证码不能为空");
        }
        String phonecode = redisTemplate.opsForValue().get(user.getTelephone());

        System.out.println(phonecode);

        if(phonecode==null){
            return new ResponseData(ResultStateCode.FAIL,"验证码已过期");
        }else if(!user.getCode().equals(phonecode)){
            return new ResponseData(ResultStateCode.FAIL,"验证码不正确");
        }
        //判断校验结果(校验错误）
        System.out.println(user);
        if (result.hasFieldErrors()) {
            Map<String, String> msgs = new HashMap<>();
            result.getFieldErrors().forEach(e -> {
                msgs.put(e.getField(), e.getDefaultMessage());

                System.out.println(msgs.get(e.getField()));
            });
            return new ResponseData(ResultStateCode.FAIL,"无效参数",msgs);
        }

        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("telephone",user.getTelephone());
        User user1=userService.getOne(queryWrapper);

        if(user1!=null){
            return new ResponseData(ResultStateCode.FAIL,"该号码已注册");
        }
        user.setStatus("y");
        user.setRegTime(MallUtils.getNow());
        user.setNickname("游客"+(int)(Math.random() * 90000 + 10000));
        user.setAvator("https://pudding-1251768607.cos.ap-nanjing.myqcloud.com/test/38461629469914499.jpg");
        userService.save(user);
        return new ResponseData(ResultStateCode.SUCCESS,"注册成功");
    }
}
